package com.cjx.admin.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cjx.admin.api.AdminUserService;
import com.cjx.admin.dao.AdminOrgUserMapper;
import com.cjx.admin.dao.AdminUserMapper;
import com.cjx.admin.dao.AdminUserRoleMapper;
import com.cjx.admin.dto.*;
import com.cjx.admin.entity.AdminOrgUserEntity;
import com.cjx.admin.entity.AdminUserEntity;
import com.cjx.admin.entity.AdminUserRoleEntity;
import com.cjx.auth.feign.AuthFeign;
import com.cjx.common.api.CommonResult;
import com.cjx.common.api.ResultCode;
import com.cjx.common.exception.Asserts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *@Description 用户服务impl
 *@Verson v1.0.0
 *@Author cjunxian
 *@Date
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class AdminUserServiceImpl extends ServiceImpl<AdminUserMapper, AdminUserEntity> implements AdminUserService {

    @Autowired
    AuthFeign authFeign;

    @Autowired
    AdminUserMapper adminUserMapper;

    @Autowired
    AdminUserRoleMapper adminUserRoleMapper;

    @Autowired
    AdminOrgUserMapper adminOrgUserMapper;

    @Override
    public CommonResult login(String username, String password) {

        if(StrUtil.isEmpty(username) || StrUtil.isEmpty(password)){
            Asserts.fail(ResultCode.CERTIFICATE_ERROR);
        }

        Map<String,String> params  = new HashMap<>();
        params.put("grant_type","password");
        params.put("client_secret","cjx-secret");
        params.put("client_id","cjx-alibaba");
        params.put("username",username);
        params.put("password",password);
        CommonResult res = authFeign.postAccessToken(params);
        if((ResultCode.SUCCESS.getCode() == res.getCode())&& ObjectUtil.isNotNull(res.getData())){
            return res;
        }else {
            return CommonResult.failed("登陆失败！原因："+res.getMessage());
        }
    }

    @Override
    public AdminUserInfoDTO getUserByUsername(String username) {

        AdminUserInfoDTO userDTO;
        LambdaQueryWrapper<AdminUserEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AdminUserEntity::getUsername,username);
        AdminUserEntity userEntity = adminUserMapper.selectOne(wrapper);
        if(ObjectUtil.isNotNull(userEntity)){
            userDTO = new AdminUserInfoDTO();
            BeanUtil.copyProperties(userEntity,userDTO);
        }else{
            return null;
        }
        List<AdminRoleDTO> rolesByUserId = adminUserRoleMapper.getRolesByUserId(userDTO.getId());
        userDTO.setRoles(rolesByUserId);
        return userDTO;
    }

    @Override
    public AdminUserDTO addUser(AdminUserDTO user) {

        LambdaQueryWrapper<AdminUserEntity> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(AdminUserEntity::getUsername,user.getUsername());
        if(adminUserMapper.selectCount(userWrapper) > 0){
            Asserts.fail("已经存在该用户！");
        }

        //密码加密
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encodePassword = passwordEncoder.encode(user.getPassword());
        user.setPassword(encodePassword);

        AdminUserEntity userEntity = new AdminUserEntity();
        BeanUtil.copyProperties(user,userEntity);

        adminUserMapper.insert(userEntity);

        if(CollectionUtil.isEmpty(user.getOrgs())){
            Asserts.fail("机构不能为空！");
        }else {
            for (AdminOrgUserDTO org : user.getOrgs()) {
                AdminOrgUserEntity orgUserEntity = new AdminOrgUserEntity();
                orgUserEntity.setOperatorId(user.getOperatorId());
                orgUserEntity.setUserId(userEntity.getId());
                orgUserEntity.setOrgId(org.getOrgId());
                orgUserEntity.setOrgPath(org.getOrgPath());
                adminOrgUserMapper.insert(orgUserEntity);
            }
        }

        //给用户绑定角色
        if(CollectionUtil.isNotEmpty(user.getRoles())){
            for (AdminUserRoleDTO role : user.getRoles()) {
                AdminUserRoleEntity userRoleEntity = new AdminUserRoleEntity();
                userRoleEntity.setOperatorId(user.getOperatorId());
                userRoleEntity.setUserId(userEntity.getId());
                userRoleEntity.setRoleId(role.getId());
                adminUserRoleMapper.insert(userRoleEntity);
            }
        }

        BeanUtil.copyProperties(userEntity,user);
        return user;
    }

    @Override
    public AdminUserDTO updateUser(AdminUserDTO user) {

        LambdaQueryWrapper<AdminUserEntity> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(AdminUserEntity::getUsername,user.getUsername());
        AdminUserEntity userEntity = adminUserMapper.selectOne(userWrapper);
        if(ObjectUtil.isNull(userEntity)){
            Asserts.fail("该用户不存在！");
        }

        //密码加密
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encodePassword = passwordEncoder.encode(user.getPassword());
        user.setPassword(encodePassword);

        BeanUtil.copyProperties(user,userEntity);

        //先删
        LambdaQueryWrapper<AdminOrgUserEntity> ouw = new LambdaQueryWrapper<>();
        ouw.eq(AdminOrgUserEntity::getUserId,user.getId());
        adminOrgUserMapper.delete(ouw);

        if(CollectionUtil.isEmpty(user.getOrgs())){
            Asserts.fail("机构不能为空！");
        }else {
            for (AdminOrgUserDTO org : user.getOrgs()) {
                AdminOrgUserEntity orgUserEntity = new AdminOrgUserEntity();
                orgUserEntity.setOperatorId(user.getOperatorId());
                orgUserEntity.setUserId(userEntity.getId());
                orgUserEntity.setOrgId(org.getOrgId());
                orgUserEntity.setOrgPath(org.getOrgPath());
                adminOrgUserMapper.insert(orgUserEntity);
            }
        }

        //先删
        LambdaQueryWrapper<AdminUserRoleEntity> urw = new LambdaQueryWrapper<>();
        urw.eq(AdminUserRoleEntity::getUserId,user.getId());
        adminUserRoleMapper.delete(urw);

        //给用户绑定角色
        if(CollectionUtil.isNotEmpty(user.getRoles())){
            for (AdminUserRoleDTO role : user.getRoles()) {
                AdminUserRoleEntity userRoleEntity = new AdminUserRoleEntity();
                userRoleEntity.setOperatorId(user.getOperatorId());
                userRoleEntity.setUserId(userEntity.getId());
                userRoleEntity.setRoleId(role.getId());
                adminUserRoleMapper.insert(userRoleEntity);
            }
        }

        return user;
    }


}
